<?php

namespace app\admin\controller\facrm\workweixin;

use app\admin\model\Admin;
use app\common\controller\Backend;
use EasyWeChat\Factory;

use  app\admin\model\facrm\qywx\User as QywxUser;
use fast\Random;
use think\Db;
use think\Exception;

/**
 * 企业员工
 * @icon fa fa-circle-o
 */
class Users extends Backend
{

    protected $model = null;
    protected $distinguish = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->request->filter(['strip_tags']);
        $this->model = new QywxUser();

    }

    /**
     * 列表
     * @return string|\think\response\Json
     * @throws Exception
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)->fetchSql(false)
                ->count();
            $list = $this->model
                ->where($where)
                ->field('weigh', true)
                ->with([
                    'admin' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                ])
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 同步员工
     */
    public function syn()
    {
        set_time_limit(0);
        $key = "work_weixin_set";
        $settingModel = new \app\admin\model\facrm\Setting();
        $row = $settingModel->where('key', $key)->find();
        if (!$row) $this->error(__("企业微信未配置"));
        $values = json_decode($row['values'], true);//获取器不知道为什么失效了
        if (!$values) $this->error(__("企业微信未配置1"));


        $config = [
            'corp_id' => $values['corp_id'],
            'secret' => $values['agent_secret'],
            'agent_id' => $values['agent_id'],
            //'agent_secret' => $values['agent_secret'],
        ];
        try {
            $app = Factory::work($config);
            $result = $app->user->getDetailedDepartmentUsers(1, true);
        } catch (\Exception $e) {
            $this->error($e->getMessage());

        }
        if (!$result || $result['errcode'] != '0') {
            $errmsg = isset($result['errmsg']) ? $result['errmsg'] : 'null';
            $this->error(__("获取失败：" . $errmsg));
        }
        $userlist = $result['userlist'];
        $result = 0;
        foreach ($userlist as $user) {
            //判断系统是否存在
            $qywxUser = QywxUser::getUser($user['userid'], $values, $user);
            if ($qywxUser) $result++;
        }
        $this->success("成功同步{$result}条");
    }


}
